// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import Fk
import Fk.Components.LunarLTK
import Fk.Pages.LunarLTK
import Fk.Components.Common

MetroButton {
  id: root
  property string skill
  property var extra_data 
  property var choices : (extra_data !== undefined) ? extra_data.choices : []
  property var all_choices : (extra_data !== undefined) ? extra_data.all_choices : []
  property var default_choice : (extra_data !== undefined) ? extra_data.default_choice : []
  property bool detailed: (extra_data !== undefined) ? extra_data.detailed : false
  property var answer : default_choice
  property int max_num : (extra_data !== undefined) ? extra_data.max_num : 1
  property bool list_visible: false

  text: Util.processPrompt(skill)

  onAnswerChanged: {
    if (!answer) return;
    Lua.call("UpdateRequestUI", "Interaction", "1", "update", answer);
  }

  function listChanged(val) { 
    if (val.length == 0) {
      answer = []; 
    } else {
      let list = [];
      val.forEach(id => {
        list.push(all_choices[id]);
      });
      answer = list;    
    }
    default_choice = answer;
  }

  onClicked: {
    if (detailed) {
      roomScene.popupBox.sourceComponent =
        Qt.createComponent(AppPath + "/packages/sanshe/qml/DetailedCheckBox.qml");
    } else {
      roomScene.popupBox.sourceComponent =
        Qt.createComponent(AppPath + "/packages/sanshe/qml/CheckBox.qml");
    }
    
    const box = roomScene.popupBox.item;
    box.options = choices;
    box.all_options = all_choices;
    box.skill_name = skill;
    box.max_num = max_num;
    box.onUpdate = listChanged;
    box.default_choice = default_choice;
    all_choices.forEach((i, id) => {
      if (default_choice.length > 0 && default_choice.indexOf(i) !== -1) {
        box.result.push(id);
      }
    });
    box.visible = !list_visible;
    list_visible = !list_visible;
  }

}

